import config from './config';
import regular from './regular.js';
import api from './api';
import common from './common.js';
import store from 'store';
// #ifdef APP-PLUS
import permision from "@/js_sdk/wa-permission/permission.js"
// #endif
// if(sys.platform=='ios'){  
//               plus.runtime.openURL("app-settings://");  
//              }else{  
//               var main = plus.android.runtimeMainActivity();  
//               var Intent = plus.android.importClass("android.content.Intent");  
//               //可能应该直接进入应用列表的权限设置？=> android.settings.APPLICATION_SETTINGS  
//               var mIntent = new Intent('android.settings.LOCATION_SOURCE_SETTINGS');  
//               main.startActivity(mIntent);  
//              }  

const user = {
    /*
    微信小程序登录
    */
    async wxlogin(cb=null,isRefresh = false) {
        if (store.state.userInfo && !isRefresh) {
            cb && cb(store.state.userInfo)
            return
        };
        const user = this;
        if(!user.isWxProfile()){
            console.log('微信没有授权');
            cb && cb(false)
            return
        }
        const [lErr,lRes] = await uni.login();
        if(!lRes.code){
           this.wxlogin();
           return
        }
        const code  = lRes.code;
        console.log('微信code',code);
        const wxUserInfo = uni.getStorageSync('wxUserInfo');
        let paramData = {
            code,
            wxMemberInfo:wxUserInfo,
        };
        const res = await api.loginByWeixin(paramData);
        if (res.data.code == config.RESOK) {
            let userInfo = res.data.data;
            userInfo = user.normalFilter(userInfo);
            store.dispatch('setUserInfo', userInfo);
            getApp().globalData.openid = userInfo.weixinOpenid;
            console.log('app.globalData.openid',getApp().globalData.openid);
            cb && cb(userInfo);
        } else{
            console.log('loginByWeixin 接口报错');
            console.log(res.data.msg);
            cb && cb(false)
        }
    },
    /*
    是否微信授权
    */
   isWxProfile(){
       return uni.getStorageSync('wxUserInfo') ? true : false;
   },
    // 获取定位
    async userLocation(isRefresh = false, callback = null, getAddCode = true) {
        if (store.state.userLocation && !isRefresh) {
            common.callback(callback, store.state.userLocation);
            return
        };
        
        const [locErr, locRes] = await uni.getLocation({
            type: 'gcj02',
        });
        console.log("locErr: " + JSON.stringify(locErr));
        console.log("locRes: " + JSON.stringify(locRes));

        if (locErr) {
            //微信端逻辑
            //#ifdef MP-WEIXIN
            if (locErr.errMsg === 'getLocation:fail auth deny') {
                const [sErr, sRes] = await uni.showModal({
                    title: '提示',
                    content: '没有授权地位权限，是否去设置',
                    showCancel: true,
                    cancelText: '取消',
                    confirmText: '去设置',
                });

                if (sRes.confirm) {
                    const [oErr, oRes] = await uni.openSetting()
                    console.log(oRes)
                    let authSetting = oRes.authSetting;
                    if (authSetting['scope.userLocation']) {
                        user.userLocation(isRefresh, callback)
                    } else {
                        common.showTip('定位授权取消！', 'none')
                        store.dispatch('setUserLocation', config.locationDefault);
                        common.callback(callback, config.locationDefault);
                    }
                } else {
                    store.dispatch('setUserLocation', config.locationDefault);
                    common.callback(callback, config.locationDefault);
                }
                return
            }
            //#endif
            //app端逻辑
            // #ifdef APP-PLUS
            
            // #endif
            common.showTip(locErr.errMsg, 'none')
            store.dispatch('setUserLocation', config.locationDefault);
            common.callback(callback, config.locationDefault);
        }
        if (locRes) {
            let data = {
                lat: locRes.latitude,
                lng: locRes.longitude,
            }
            if (getAddCode) {
                let res = await this.getAddCode(data)
                console.log('this.getAddCode', res)
                data = Object.assign({}, data, res.ad_info, {
                    address: res.address,
                });

                const {
                    lng,
                    lat
                } = common.qqMapTransBMap(data.lng, data.lat)
                data.bdlng = lng;
                data.bdlat = lat;
                store.dispatch('setUserLocation', data);
            }
            common.callback(callback, data);
        }
        // console.log("store.state.userLocation: " + JSON.stringify(store.state.userLocation));
    },
    /*获取中文地址信息*/
    async getAddCode(data) {
        let paras = {
            location: `${data.lat},${data.lng}`,
            key: config.MAP_KEY,
            get_poi: 1
        }
        const [err, res] = await uni.request({
            url: 'https://apis.map.qq.com/ws/geocoder/v1/',
            method: 'GET',
            data: paras,
        });
        return new Promise((qres, qrej) => {
            qres(res.data.result)
        })
    },
    //获取openid
    async getOpenid(cb = null){
        let openid = null;
        const [lErr, lRes] = await uni.login();
        if (lErr) return
        if (!lRes.code) {
            this.getOpenid();
            return
        }
        const res = await api.getWeixinInfo({
            code: lRes.code
        })
        if (res.data.code == config.RESOK) {
            openid = res.data.data.openid;
             cb && cb(openid)
        }
        return new Promise((pres,prej)=>{
            pres(openid)
        })
    },
    //绑定小程序openid
    async bindOpenid(cb = null) {
        console.log(' 绑定小程序 bindOpenid  return');
        return
        // #ifdef MP-WEIXIN
        let openid = null;
        const [lErr, lRes] = await uni.login();
        if (lErr) return
        if (!lRes.code) {
            this.bindOpenid();
            return
        }
        const res = await api.getWeixinInfo({
            code: lRes.code
        })
        if (res.data.code == config.RESOK) {
            openid = res.data.data.openid;
        }
        const bres = await api.updateOpenId({
            openId: openid,
            OpenId: openid,
            openid,
        })
        console.log('bres')
        console.log(bres);
        cb && cb(openid)
        // #endif
    },

    async userInfo(that) {

        const user = this;
        const res = await that.$api.authInfo();
        return new Promise((qres, qrej) => {
            if (res.data.status == that.$config.RESOK) {
                let info = res.data.data.member;
                // this.setUserInfo(Object.assign({},this.userInfo,info)); 
                // userInfo = that.$user.normalFilter(userInfo);
                //  store.dispatch('setUserInfo', userInfo);
                qres(userInfo)
            } else {
                qres(null)
            }
        })
    },
    async loginAfter() {
        console.log('loginAfter')
        const pages = getCurrentPages();
        const page = pages[pages.length - 1];
        if (config.TABBAR.includes(page.route)) {
            const notRes = await api.noticeStatus({
                user_details_id
            });
            if (notRes.data.status == config.RESOK) {
                uni.showTabBarRedDot({
                    index: 2
                })
            } else {
                uni.hideTabBarRedDot({
                    index: 2
                })
            }
        }
    },
    //提示去登录
    goLoginTip() {
        uni.showModal({
            title: '提示',
            content: '当前是游客身份，请先登录',
            showCancel: true,
            confirmText: '去登录',
            cancelText: '返回',
            success: res => {
                if (res.confirm) {
                    common.hisPath();
                    uni.redirectTo({
                        url: '/pages/login/login',
                    })
                }
            },
        });
    },

    /*过滤*/
    normalFilter(userInfo) {
    	if(userInfo.avatar && userInfo.avatar.indexOf('http') == -1){
    		userInfo.avatar = config.httpImgs + userInfo.avatar
    	}
		if(userInfo.davatar && userInfo.davatar.indexOf('http') == -1){
			userInfo.davatar = config.httpImgs + userInfo.davatar
		}
        return userInfo
    },
}

export default user;
